﻿using CleanArchitecture.Core.Events;
using CleanArchitecture.Core.Handlers;
using CleanArchitecture.Core.Interfaces;
using CleanArchitecture.Infrastructure.Entities;
using CleanArchitecture.Infrastructure.Entities.System.Notice;
using CleanArchitecture.Infrastructure.Interfaces;
using CleanArchitecture.Infrastructure.Interfaces.Notice;
using System;
using System.Linq;

namespace CleanArchitecture.Infrastructure.Services.Notice
{
    public class SystemNoticeService : ISystemNoticeService
    {
        private readonly IRepository<SystemNotice> _systemnoticeRepository;
        private readonly IDomainEventDispatcher _eventDispatcher;
        public SystemNoticeService(IRepository<SystemNotice> systemNoticeRepo,
            IDomainEventDispatcher eventDispatcher)
        {
            this._systemnoticeRepository = systemNoticeRepo;
            this._eventDispatcher = eventDispatcher;
        }
        public void DeleteSystemNotice(SystemNotice notice)
        {
            if (notice == null)
                throw new ArgumentNullException(nameof(notice));

            notice.IsActive = EntityEnumConfig.YesorNo.No;
            notice.NoticeTitle = "Deleted-" + notice.NoticeTitle;
            _systemnoticeRepository.Update(notice);

            if (!string.IsNullOrEmpty(notice.SysLogMsg))
                //event notification
                _eventDispatcher.Dispatch(new EntityDeletedEvent<SystemNotice>(notice));
        }

        public SystemNotice GetSystemNoticeById(int noticeId)
        {
            if (noticeId == 0) return null;
            return _systemnoticeRepository.GetById(noticeId);
        }

        public void InsertSystemNotice(SystemNotice notice)
        {
            if(notice == null) throw new ArgumentNullException(nameof(notice));

            _systemnoticeRepository.Insert(notice);

            //event notification
            if (!string.IsNullOrEmpty(notice.SysLogMsg))
                _eventDispatcher.Dispatch(new EntityInsertedEvent<SystemNotice>(notice));
        }

        public IViewPagedList<SystemNotice> GetSystemNoticesByPage(int pageIndex = 0, int pageSize = int.MaxValue)
        {
            var query = _systemnoticeRepository.TableNoTracking.Where(n => n.IsActive == EntityEnumConfig.YesorNo.YES)
                                           .OrderByDescending(n => n.CreatedOnTimeUtc);
            var notices = new ViewPagedList<SystemNotice>(query, pageIndex, pageSize);
            return notices;
        }
    }
}
